<?php

namespace App\Store\Controllers\Goods;

use App\Common\Services\Common;
use App\Store\Models\Goods\GoodsAllotInfolist;
use App\Store\Models\Goods\GoodsReturnInfolist;
use App\Store\Models\Goods\GoodsStockinPrint;
use App\Store\Models\OldMaterial\Stock;
use App\Store\Models\Order\OrderSalesGoods;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Common\Services\Store\Common as StoreCommon;
use App\Common\Services\CommonExcelExport;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\GoodsBrand;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Basic\GoodsContent;
use App\Store\Models\Basic\GoodsCraft;
use App\Store\Models\Basic\GoodsPricetype;
use App\Store\Models\Basic\GoodsStone;
use App\Store\Models\Basic\GoodsStyle;
use App\Store\Models\Basic\PaytypeList;
use App\Store\Models\Basic\Supply;
use App\Store\Models\Goods\GoodsStockin;
use App\Store\Models\Goods\GoodsStockinInfolist;
use App\Store\Models\Goods\GoodsStockinPaymoneylog;
use App\Store\Models\Goods\GoodsStockList;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\Excel\DownloadTemp;
use App\Store\Services\Financial;
use App\Store\Services\Goods\Goods;
use Illuminate\Support\Facades\DB;
use App\Store\Validate\Goods\GoodsStockin as ValidateGoodsGoodsStockin;

/**
 * 商品入库信息
 */
class GoodsStockinController extends Controller
{
    /**
     * 商品入库
     */
    public function getlist(Request $request)
    {

        $list = GoodsStockin::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 商品入库明细
     */
    public function getgoodsstockininfo(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = GoodsStockin::with(['storeinfo'])->where(['id' => $id, 'cp_id' => $cp_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $where = [];
        $order_number = $request->order_number;
        if ($order_number != '') {
            $where[] = ['goods_sn_code', 'like', '%' . $order_number . '%'];
        }

        $goods_style_id = intval($request->goods_style_id);
        if ($goods_style_id > 0) {
            $where[] = ['goods_style_id', $goods_style_id];
        }

        $goods_category_id = intval($request->goods_category_id);
        if ($goods_category_id > 0) {
            $where[] = ['goods_category_id', $goods_category_id];
        }

        $audit_status = intval($request->audit_status);
        // if ($audit_status > 0) {
        //     $where[] = ['audit_status', $audit_status];
        // }


        //获取分类查询信息
        $list1 = GoodsStockinInfolist::with(['goods_category'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where)
            ->groupBy('goods_category_id')
            ->select('goods_category_id', DB::raw('sum(count) as count,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(label_price*count) as label_price,sum(label_price_new*count) as label_price_new,sum(total_netglod_weight) as netglod_weight,sum(total_netglod_weight_new) as netglod_weight_new,sum(total_piece_weight) as piece_weight,sum(total_piece_weight_new) as piece_weight_new,sum(total_cost_fee) as total_price'))
            ->orderBy('audit_status', 'desc')
            ->orderBy('audit_at', 'desc')
            ->get()
            ->toArray();

        if ($list1) {
            foreach ($list1 as $k => $v) {
                if ($v['audit_failed_count'] + $v['audit_success_count'] >= $v['count']) {
                    $status = 3;
                } elseif ($v['audit_failed_count'] + $v['audit_success_count'] < $v['count']) {
                    if ($v['audit_failed_count'] == 0 && $v['audit_success_count'] == 0) {
                        $status = 1;
                    } else {
                        $status = 2;
                    }
                }
                $list1[$k]['audit_status'] = $status;

                if ($audit_status > 0) {
                    if ($status != $audit_status) {
                        unset($list1[$k]);
                    }
                }
            }
            $list1 = array_values($list1);
        }


        //按照类别汇总
        //按照款式汇总
        $list2 = GoodsStockinInfolist::with(['goods_style'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where)
            ->groupBy('goods_style_id')
            ->select('goods_style_id', DB::raw('sum(count) as count,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(label_price*count) as label_price,sum(label_price_new*count) as label_price_new,sum(total_netglod_weight) as netglod_weight,sum(total_netglod_weight_new) as netglod_weight_new,sum(total_piece_weight) as piece_weight,sum(total_piece_weight_new) as piece_weight_new,sum(total_cost_fee) as total_price'))
            ->orderBy('audit_status', 'desc')
            ->orderBy('audit_at', 'desc')
            ->get()
            ->toArray();


        if ($list2) {
            foreach ($list2 as $k => $v) {
                if ($v['audit_failed_count'] + $v['audit_success_count'] >= $v['count']) {
                    $status = 3;
                } elseif ($v['audit_failed_count'] + $v['audit_success_count'] < $v['count']) {
                    if ($v['audit_failed_count'] == 0 && $v['audit_success_count'] == 0) {
                        $status = 1;
                    } else {
                        $status = 2;
                    }
                }
                $list2[$k]['audit_status'] = $status;

                if ($audit_status > 0) {
                    if ($status != $audit_status) {
                        unset($list2[$k]);
                    }
                }
            }
            $list2 = array_values($list2);
        }
        //查询子订单详情
        $list3_query = GoodsStockinInfolist::with(['storeinfo', 'goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info', 'goods_brand', 'goods_content'])
            ->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where);
        if ($audit_status > 0) {
            $list3_query->where('audit_status', $audit_status);
        }
        $list3_query->orderBy('audit_status', 'desc')->orderBy('audit_at', 'desc');

        $page = $request->page ?? 0;
        $limit = $request->limit ?? 10;
        if ($page == 0) {
            $list3 = $list3_query->get()->toArray();
        } else {
            $list3 = $list3_query->paginate($limit)->toArray();
            $list3 = Common::paginateDataToArray($list3);
        }


        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info, 'list1' => $list1, 'list2' => $list2, 'list3' => $list3]]);
    }

    /**
     * 新增商品入库
     */
    public function dopostadd(Request $request)
    {

        $req_data = $request->only([
            'store_id', 'goods_sn_code', 'goods_img', 'pricetype', 'odds', 'goods_name', 'goods_style_id', 'goods_category_id', 'stockin_at', 'supply_id', 'count', 'gramprice_fee', 'label_price',
            'pieceprice_fee', 'piece_weight', 'netglod_weight', 'content', 'costglod_price', 'costpiece_fee', 'costgram_fee', 'piececost_fee', 'goods_craft_id', 'c_no', 's_no',
            'gemstone_fee1', 'gemstone_fee2', 'add_fee1', 'add_fee2', 'goods_brand_id', 'cf_no', 'cf_no_gia', 'cf_fee', 'main_stone_weigth', 'main_stone_count', 'other_stone_weigth',
            'other_stone_count', 'color', 'clarity', 'main_stone_val', 'other_stone_val', 'cut', 'goods_pricetype_id', 'goods_stone_id', 'procure_at', 'paytype_id', 'paymoney', 'remark',
            'total_piece_weight', 'total_netglod_weight', 'is_code_more', 'goods_content_id'
        ]);

        $Validate = new ValidateGoodsGoodsStockin();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);

        $req_data['stockin_at'] = (isset($req_data['stockin_at']) && !empty($infodata['stockin_at'])) ? strtotime($infodata['stockin_at']) : time();
        $req_data['procure_at'] = (isset($req_data['procure_at']) && !empty($infodata['procure_at'])) ? strtotime($infodata['procure_at']) : time();

        try {
            $res = (new Goods())->stockInAdd($req_data, $accountinfo, 1);
            if ($res == true) {
                return response()->json(['code' => '000', 'msg' => '新增商品入库成功']);
            }
        } catch (\Exception $e) {

            return response()->json(['code' => '001', 'msg' => '商品添加失败' . $e->getMessage()]);
        }

    }

    /**
     *
     * 电子秤入库
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|true
     */
    public function doelectronicadd(Request $request)
    {
        $goodscheck = [
            'store_id', 'goods_sn_code', 'goods_img', 'pricetype', 'odds', 'goods_name', 'goods_style_id', 'goods_category_id', 'stockin_at', 'supply_id', 'count', 'gramprice_fee', 'label_price',
            'pieceprice_fee', 'piece_weight', 'netglod_weight', 'content', 'costglod_price', 'costpiece_fee', 'costgram_fee', 'piececost_fee', 'goods_craft_id', 'c_no', 's_no',
            'gemstone_fee1', 'gemstone_fee2', 'add_fee1', 'add_fee2', 'goods_brand_id', 'cf_no', 'cf_no_gia', 'cf_fee', 'main_stone_weigth', 'main_stone_count', 'other_stone_weigth',
            'other_stone_count', 'color', 'clarity', 'main_stone_val', 'other_stone_val', 'cut', 'goods_pricetype_id', 'goods_stone_id', 'procure_at', 'paytype_id', 'paymoney', 'remark',
            'total_piece_weight', 'total_netglod_weight', 'is_code_more', 'goods_content_id'
        ];
        $scaleData = $request->all();
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        foreach ($scaleData as $data) {
            $Validate = new ValidateGoodsGoodsStockin();
            if (!$Validate->check($data)) {
                return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
            }
        }

        // 数据根据门店分组
        $groupData = [];
        foreach ($scaleData as $item) {
            $groupData[$item['store_id']][] = $item;
        }


        $storeList = SiteStore::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->get()
            ->pluck(null, 'id')
            ->toArray();

        // 按照门店分组进行数据入库
        foreach ($groupData as $storeId => $storeGoods) {
            $store = $storeList[$storeId] ?? [];
            if (empty($store)) {
                return response()->json(['code' => '001', 'msg' => '无效门店参数']);
            }

            $goodsCategoryIds = array_column($storeGoods, 'goods_category_id');

            $cateList = GoodsCategory::query()
                ->where(['cp_id' => $cp_id, 'is_del' => 1, 'store_id' => $storeId])
                ->whereIn('id', $goodsCategoryIds)
                ->get()
                ->pluck(null, 'id')
                ->toArray();

            $goodsData = [];
            $order_sncode = StoreCommon::createOrderSn();
            foreach ($scaleData as $goods) {

                $isRepeatRes = $this->isRepeatGoodsSnCode(['goods_sn_code' => $goods['goods_sn_code'], 'cp_id' => $cp_id]);
                if ($isRepeatRes['code'] == '001') {
                    return response()->json(['code' => '001', 'msg' => $isRepeatRes['msg']]);
                }

                $categoryinfo = $cateList[$goods['goods_category_id']] ?? [];

                $is_gram = $categoryinfo['is_gram'] ?? 0;
                if (empty($categoryinfo)) {
                    return response()->json(['code' => '001', 'msg' => '该分类不存在']);
                }
                if ($goods['is_code_more'] == 2 && $is_gram == 2) {
                    return response()->json(['code' => '001', 'msg' => '该分类为非克重商品，不可选择一码多货']);
                }
                foreach ($goods as $k => $v) {
                    if (!in_array($k, $goodscheck)) {
                        unset($goods[$k]);
                    }
                }
                $goods['cp_id'] = $cp_id;
                $goods['pieceprice_fee'] = empty($goods['pieceprice_fee']) ? 0 : $goods['pieceprice_fee'] * 100;
                $goods['costpiece_fee'] = empty($goods['costpiece_fee']) ? 0 : $goods['costpiece_fee'] * 100;
                $goods['costgram_fee'] = empty($goods['costgram_fee']) ? 0 : $goods['costgram_fee'] * 100;
                $goods['gramprice_fee'] = empty($goods['gramprice_fee']) ? 0 : $goods['gramprice_fee'] * 100;
                $goods['piececost_fee'] = empty($goods['piececost_fee']) ? 0 : $goods['piececost_fee'] * 100;
                $goods['costglod_price'] = empty($goods['costglod_price']) ? 0 : $goods['costglod_price'] * 100;
                $goods['paymoney'] = empty($goods['paymoney']) ? 0 : $goods['paymoney'] * 100;
                $goods['add_fee1'] = empty($goods['add_fee1']) ? 0 : $goods['add_fee1'] * 100;
                $goods['add_fee2'] = empty($goods['add_fee2']) ? 0 : $goods['add_fee2'] * 100;

                $goods['stockin_at'] = (isset($goods['stockin_at']) && !empty($goods['stockin_at'])) ? strtotime($goods['stockin_at']) : time();
                $goods['procure_at'] = (isset($goods['procure_at']) && !empty($goods['procure_at'])) ? strtotime($goods['procure_at']) : time();
                $goods['order_sncode'] = $order_sncode;

                // 是否一码多货：1否，2是
                $goods['total_piece_weight'] = isset($goods['piece_weight']) ? doubleval($goods['piece_weight'] * $goods['count']) : 0;
                $goods['total_piece_weight_new'] = isset($goods['piece_weight']) ? $goods['piece_weight'] * $goods['count'] : 0;

                if ($goods['is_code_more'] == 2) {
                    $goods['total_netglod_weight'] = empty($goods['total_netglod_weight']) ? ($goods['total_piece_weight_new'] ?? 0) : $goods['total_netglod_weight'];
                    $goods['total_netglod_weight_new'] = $goods['total_netglod_weight'] ?? 0;
                    if (!isset($goods['total_netglod_weight']) || $goods['total_netglod_weight'] <= 0) {
                        return response()->json(['code' => '001', 'msg' => '一码多货必须输入总金重']);
                    }
                    $goods['total_cost_fee'] = bcmul(($goods['costglod_price'] ?? 0), $goods['total_netglod_weight']);
                } else {
                    $goods['total_netglod_weight'] = isset($goods['netglod_weight']) ? doubleval($goods['netglod_weight'] * $goods['count']) : 0;
                    $goods['total_netglod_weight_new'] = isset($goods['netglod_weight']) ? $goods['netglod_weight'] * $goods['count'] : 0;

                    if ($is_gram == 1) {
                        if ($goods['total_netglod_weight'] <= 0 || $goods['netglod_weight'] <= 0) {
                            return response()->json(['code' => '001', 'msg' => '总金重以及金重不可小于0']);
                        }
                        $goods['total_cost_fee'] = bcmul((string)($goods['costgram_fee'] + $goods['costglod_price']), $goods['total_netglod_weight'], 0) + $goods['costpiece_fee'] * $goods['count'];
                    } else {
                        $goods['piece_weight'] = isset($goods['piece_weight']) ? doubleval($goods['piece_weight']) : 0;
                        if ($goods['total_piece_weight'] < 0 || $goods['piece_weight'] < 0) {
                            return response()->json(['code' => '001', 'msg' => '总件重以及件重不可小于0']);
                        }

                        $goods['total_cost_fee'] = $goods['piececost_fee'] * $goods['count'];
                    }
                }
                // 删除前端传过来的多余数据
                // unset($goods['goods_cabinetgroup_name'], $goods['goods_category_item'], $goods['goods_style_item'], $goods['is_gram'], $goods['is_sujin'], $goods['is_virtually'], $goods['metal_name'], $goods['style_name']);

                $goods['costglod_price'] = empty($goods['costglod_price']) ? 0 : $goods['costglod_price'];
                $goods['costpiece_fee'] = empty($goods['costpiece_fee']) ? 0 : $goods['costpiece_fee'];
                $goods['costgram_fee'] = empty($goods['costgram_fee']) ? 0 : $goods['costgram_fee'];
                $goods['gramprice_fee'] = empty($goods['gramprice_fee']) ? 0 : $goods['gramprice_fee'];
                $goods['goods_brand_id'] = empty($goods['goods_brand_id']) ? 0 : $goods['goods_brand_id'];
                $goods['goods_content_id'] = empty($goods['goods_content_id']) ? 0 : $goods['goods_content_id'];
                $goods['goods_craft_id'] = empty($goods['goods_craft_id']) ? 0 : $goods['goods_craft_id'];
                $goods['goods_stone_id'] = empty($goods['goods_stone_id']) ? 0 : $goods['goods_stone_id'];
                $goods['netglod_weight'] = empty($goods['netglod_weight']) ? 0 : $goods['netglod_weight'];
                $goods['netglod_weight_new'] = $goods['netglod_weight'] ?? 0;
                $goods['piece_weight'] = empty($goods['piece_weight']) ? 0 : $goods['piece_weight'];
                $goods['pieceprice_fee'] = empty($goods['pieceprice_fee']) ? 0 : $goods['pieceprice_fee'];
                $goods['total_piece_weight'] = empty($goods['total_piece_weight']) ? 0 : $goods['total_piece_weight'];
                $goods['total_piece_weight_new'] = empty($goods['total_piece_weight_new']) ? 0 : $goods['total_piece_weight_new'];

                $goodsData[] = $goods;

            }


            //处理数据类型
            foreach ($goodsData as $key => $val) {
                if ($val == '' || $val == 0) {
                    unset($goodsData[$key]);
                } else {
                    if ($key == 'piece_weight') {
                        $goodsData['piece_weight_new'] = $goodsData['piece_weight'];
                    }
                    if ($key == 'netglod_weight') {
                        $goodsData['netglod_weight_new'] = $goodsData['netglod_weight'];
                    }
                    if ($key == 'label_price') {
                        $goodsData['label_price_new'] = $goodsData['label_price'];
                    }
                }
            }


            // 处理主数据
            $mainData = [];
            $mainData['cp_id'] = $cp_id;
            $mainData['electronic_scale'] = 1; //电子秤入库
            $mainData['store_id'] = $storeId;
            $mainData['order_sncode'] = StoreCommon::createOrderSn();
            $mainData['goods_count'] = array_sum(array_column($goodsData, 'count'));
            $mainData['supply_id'] = $goodsData[0]['supply_id'] ?? 0;
            $mainData['goods_brand_id'] = $goodsData[0]['supply_id'] ?? 0;
            $mainData['paymoney'] = array_sum(array_column($goodsData, 'paymoney'));
            $mainData['create_at'] = time();
            $mainData['update_at'] = time();
            $mainData['create_account_id'] = $accountinfo['id'];
            $mainData['create_account_real_name'] = $accountinfo['real_name'];


            try {
                DB::beginTransaction();
                $pid = GoodsStockin::query()->create($mainData)->id;
                foreach ($goodsData as &$info) {
                    $info['p_id'] = $pid;
                }
                GoodsStockinInfolist::query()->insert($goodsData);
                DB::commit();

            } catch (\Exception $e) {
                DB::rollBack();
                info('电子秤入库失败' . $storeId . '原因' . $e->getMessage());
                return response()->json(['code' => '001', 'msg' => '新增商品入库失败' . $e->getMessage()]);
            }

        }
        return response()->json(['code' => '000', 'msg' => '新增商品入库成功']);


    }

    /**
     * 电子秤商品入库
     */
    public function electronicgetlist(Request $request)
    {

        $request->isgetall = 1;
        $list = GoodsStockin::electronicgetlist($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 电子秤打印完成修改状态
     */
    public function doelectronicsuccessmore(Request $request)
    {

        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        if (count($ids) <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择的商品']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $where = [
            'electronic_scale' => 1,
            'cp_id' => $cp_id
        ];
        $store_id = intval($accountinfo['store_ids']);

        if (($accountinfo['type'] == 1 || $accountinfo['type'] == 2)) {
            $where[] = ['store_id' => $store_id];
        }

        DB::beginTransaction();
        try {
            GoodsStockin::where($where)
                ->whereIN('id', $ids)
                ->update(['electronic_scale' => 2]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '操作失败']);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


    /**
     * 根据条码获取入库商品信息
     */
    public function getinfobysncode(Request $request)
    {
        $goods_sn_code = $request->goods_sn_code;
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $store_id = $request->store_id ?? intval($accountinfo['store_ids']);
        $cp_id = $accountinfo['cp_id'];
        $info = GoodsStockinInfolist::query()->with(['storeinfo', 'goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info', 'goods_brand'])
            ->when($store_id > 0, function ($query) use ($store_id) {
                $query->where('store_id', $store_id);
            })
            ->where(['cp_id' => $cp_id, 'goods_sn_code' => $goods_sn_code])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 根据主键获取入库商品信息
     */
    public function getinfobyid(Request $request)
    {
        $id = intval($request->id);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = GoodsStockinInfolist::with(['storeinfo', 'goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info', 'goods_brand'])->where(['cp_id' => $cp_id, 'id' => $id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    public function postgoodsimg(Request $request)
    {
        $id = intval($request->id);
        $goods_img = strval($request->goods_img);
        if ($goods_img == '') {
            return response()->json(['code' => '001', 'msg' => '图片未上传']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = GoodsStockinInfolist::where(['cp_id' => $cp_id, 'id' => $id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '已审核单据不可修改']);
        }

        GoodsStockinInfolist::where(['cp_id' => $cp_id, 'id' => $id])->update(['goods_img' => $goods_img, 'update_at' => time()]);


        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 编辑---单条数据编辑
     */
    public function dopostinfoedit(Request $request)
    {
        $req_data = $request->only([
            'id', 'goods_sn_code', 'goods_img', 'pricetype', 'odds', 'goods_name', 'goods_style_id', 'goods_category_id', 'stockin_at', 'supply_id', 'count', 'gramprice_fee', 'label_price',
            'pieceprice_fee', 'piece_weight', 'netglod_weight', 'content', 'costglod_price', 'costpiece_fee', 'costgram_fee', 'piececost_fee', 'goods_craft_id', 'c_no', 's_no',
            'gemstone_fee1', 'gemstone_fee2', 'add_fee1', 'add_fee2', 'goods_brand_id', 'cf_no', 'cf_no_gia', 'cf_fee', 'main_stone_weigth', 'main_stone_count', 'other_stone_weigth',
            'other_stone_count', 'color', 'clarity', 'main_stone_val', 'other_stone_val', 'cut', 'goods_pricetype_id', 'goods_stone_id', 'procure_at', 'paytype_id', 'paymoney', 'remark', 'total_piece_weight', 'total_netglod_weight', 'is_code_more', 'goods_content_id'
        ]);

        $Validate = new ValidateGoodsGoodsStockin('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $info = GoodsStockinInfolist::where(['cp_id' => $cp_id, 'id' => $req_data['id']])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '已审核单据不可修改']);
        }

        $isRepeatRes = $this->isRepeatGoodsSnCode(['goods_sn_code' => $req_data['goods_sn_code'], 'cp_id' => $cp_id, 'operator' => 'edit', 'id' => $req_data['id']]);
        if ($isRepeatRes['code'] == '001') {
            return response()->json(['code' => '001', 'msg' => $isRepeatRes['msg']]);
        }

        $categoryinfo = GoodsCategory::where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'is_del' => 1, 'id' => $req_data['goods_category_id']])->first();
        if (!$categoryinfo) {
            return response()->json(['code' => '001', 'msg' => '无效分类参数']);
        }
        if ($req_data['is_code_more'] == 2 && $categoryinfo->is_gram == 2) {
            return response()->json(['code' => '001', 'msg' => '该分类为非克重商品，不可选择一码多货']);
        }

        $infodata = $req_data;
        unset($infodata['id']);
        $infodata['stockin_at'] = isset($req_data['stockin_at']) ? ($infodata['stockin_at'] ? strtotime($infodata['stockin_at']) : 0) : 0;
        $infodata['procure_at'] = isset($req_data['procure_at']) ? ($infodata['procure_at'] ? strtotime($infodata['procure_at']) : 0) : 0;
        if ($req_data['is_code_more'] == 2) {
            $infodata['total_netglod_weight_new'] = $infodata['total_netglod_weight'] ?? 0;
            // $infodata['total_cost_fee'] = bcmul((string)($infodata['costgram_fee'] + $infodata['costglod_price']), $infodata['total_netglod_weight'], 0) + $infodata['costpiece_fee'] * $infodata['count'];
            $infodata['total_cost_fee'] = bcmul(($infodata['costglod_price'] ?? 0), ($infodata['total_netglod_weight'] ?? 0));
            if ($infodata['total_netglod_weight'] <= 0) {
                return response()->json(['code' => '001', 'msg' => '一码多货必须输入总金重']);
            }
        } else {
            // 总件重
            $infodata['total_piece_weight'] = isset($infodata['piece_weight']) ? doubleval($infodata['piece_weight'] * $infodata['count']) : 0;
            $infodata['total_piece_weight_new'] = isset($infodata['piece_weight']) ? $infodata['piece_weight'] * $infodata['count'] : 0;;
            // 总金重
            $infodata['total_netglod_weight'] = isset($infodata['netglod_weight']) ? doubleval($infodata['netglod_weight'] * $infodata['count']) : 0;
            $infodata['total_netglod_weight_new'] = $infodata['total_netglod_weight'];
            $is_gram = GoodsCategory::where(['cp_id' => $cp_id, 'is_del' => 1, 'store_id' => $info->store_id, 'id' => $infodata['goods_category_id']])->value('is_gram');
            if ($is_gram == 1) {
                if ($infodata['total_netglod_weight'] <= 0 || $infodata['netglod_weight'] <= 0) {
                    return response()->json(['code' => '001', 'msg' => '总金重以及金重不可小于0']);
                }
                $infodata['total_cost_fee'] = bcmul((string)($infodata['costgram_fee'] + $infodata['costglod_price']), $infodata['total_netglod_weight'], 0) + $infodata['costpiece_fee'] * $infodata['count'];
            } else {
                $infodata['piece_weight'] = isset($infodata['piece_weight']) ? doubleval($infodata['piece_weight']) : 0;
                if ($infodata['total_piece_weight'] < 0 || $infodata['piece_weight'] < 0) {
                    return response()->json(['code' => '001', 'msg' => '总件重以及件重不可小于0']);
                }
                $infodata['total_cost_fee'] = $infodata['piececost_fee'] * $infodata['count'];

            }
        }
        //处理数据类型
        foreach ($infodata as $key => $val) {
            if ($val == '' || $val == 0) {
                if ($info->$key) {
                    $infodata[$key] = is_numeric($info->$key) ? 0 : '';
                } else {
                    unset($infodata[$key]);
                    continue;
                }
            }

            if ($key == 'piece_weight') {
                $infodata['piece_weight_new'] = $infodata['piece_weight'];
                unset($infodata['piece_weight']);
            }
            if ($key == 'netglod_weight') {
                $infodata['netglod_weight_new'] = $infodata['netglod_weight'];
                unset($infodata['netglod_weight']);
            }
            if ($key == 'label_price') {
                $infodata['label_price_new'] = $infodata['label_price'];
                unset($infodata['label_price']);
            }

            if ($key == 'total_piece_weight') {
                unset($infodata['total_piece_weight']);
            }

            if ($key == 'total_netglod_weight') {
                unset($infodata['total_netglod_weight']);
            }
        }
        //处理数据类型
        DB::beginTransaction();
        try {
            GoodsStockinInfolist::where(['cp_id' => $cp_id, 'id' => $req_data['id']])->update($infodata);
            //更改主订单相关
            GoodsStockin::where(['cp_id' => $cp_id, 'id' => $info['p_id']])->update([
                'goods_count' => DB::raw('goods_count + ' . ($req_data['count'] - $info->count)),
                'paymoney' => DB::raw('paymoney + ' . (intval((isset($req_data['paymoney']) ? $req_data['paymoney'] : 0)) - $info->paymoney)),
                'update_at' => time(),
            ]);

            //更新库存相关
            // GoodsStockList::where((['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $info->goods_sn_code]))
            //     ->update($infodata);
            //查询新数据
            $infodata = GoodsStockinInfolist::where(['cp_id' => $cp_id, 'id' => $req_data['id']])->first()->toArray();
            Goods::changeGoodsLog($request, StoreCommon::createOrderSn(), $info->toArray(), json_encode($info->toArray()), json_encode($infodata));
            $count = $infodata['count'] - $info->count;
            $infodata['stockin_at'] = $info->stockin_at;
            Goods::goodsLog($request, 0, intval($info['store_id']), $infodata, intval($count), ($count > 0 ? 2 : 3), $info->order_sncode);
            //增加日志相关
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '编辑商品入库失败' . $e->getMessage()]);
        }


        return response()->json(['code' => '000', 'msg' => '编辑商品入库成功']);
    }

    public function dopostinfoimgedit(Request $request)
    {

        $id = intval($request->id);
        $goods_img = $request->goods_img;


        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $info = GoodsStockinInfolist::where(['cp_id' => $cp_id, 'id' => $id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '已审核单据不可修改']);
        }

        if ($goods_img == '') {
            return response()->json(['code' => '001', 'msg' => '请选择上传图片']);
        }

        GoodsStockinInfolist::where(['cp_id' => $cp_id, 'id' => $id])->update(['goods_img' => $goods_img]);

        return response()->json(['code' => '000', 'msg' => '商品图片补录成功']);
    }

    /**
     * 审核成功
     */
    public function doauditsuccess(Request $request)
    {
        $p_id = $request->p_id;

        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        $goods_style_ids = $request->goods_style_ids;
        $goods_style_ids = is_array($goods_style_ids) ? $ids : (is_array(json_decode($goods_style_ids, true)) ? json_decode($goods_style_ids, true) : []);
        $goods_category_ids = $request->goods_category_ids;
        $goods_category_ids = is_array($goods_category_ids) ? $goods_category_ids : (is_array(json_decode($goods_category_ids, true)) ? json_decode($goods_category_ids, true) : []);


        if (count($ids) == 0 && count($goods_style_ids) == 0 && count($goods_category_ids) == 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $maininfo = GoodsStockin::where(['id' => $p_id, 'cp_id' => $cp_id])->first();

        if (!$maininfo) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }


        $store_id = intval($accountinfo['store_ids']);
        if (count($goods_category_ids) > 0) {
            $infolist = GoodsStockinInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->whereIn('goods_category_id', $goods_category_ids)->get()->toArray();
        } else {

            if (count($goods_style_ids) > 0) {
                $infolist = GoodsStockinInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->whereIn('goods_style_id', $goods_style_ids)->get()->toArray();
            } else {
                $infolist = GoodsStockinInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->whereIn('id', $ids)->get()->toArray();
            }
        }


        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                //增加逻辑 入库存列表，保证条码唯一
                $isexist = GoodsStockList::where(['cp_id' => $cp_id, 'goods_sn_code' => $info['goods_sn_code'], 'is_del' => 1])->first();
                if ($isexist) {
                    return response()->json(['code' => '001', 'msg' => '条码：' . $info['goods_sn_code'] . '已存在']);
                }
                $id = $info['id'];
                GoodsStockinInfolist::where(['id' => $id, 'cp_id' => $cp_id, 'store_id' => $store_id])->update(['audit_status' => 2, 'audit_success_count' => $info['count'], 'audit_at' => time()]);
                //入库操作
                $data = $info;
                unset($data['id']);
                unset($data['p_id']);
                unset($data['audit_status']);
                unset($data['audit_at']);
                $data['create_at'] = time();
                $data['start_stockin_store_id'] = $data['store_id'];
                $data['piece_weight'] = $data['piece_weight_new'];
                $data['netglod_weight'] = $data['netglod_weight_new'];
                $data['label_price'] = $data['label_price_new'];
                $data['total_piece_weight'] = $data['total_piece_weight_new'];
                $data['total_netglod_weight'] = $data['total_netglod_weight_new'];

                GoodsStockList::create($data);
                $audit_status_count = GoodsStockinInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }

                GoodsStockin::where(['id' => $info['p_id'], 'cp_id' => $cp_id, 'store_id' => $store_id])->increment('audit_success_count', $info['count'], ['audit_status' => $audit_status, 'audit_at' => time()]);
                Goods::goodsLog($request, 0, intval($info['store_id']), $info, intval($info['count']), 1, $info['order_sncode']);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '入库单审核成功']);
    }

    /**
     * 批量审核
     */
    public function doauditsuccessmore(Request $request)
    {

        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        if (count($ids) <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择需要审核的商品']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];


        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }
        $store_id = intval($accountinfo['store_ids']);

        $maininfocount = GoodsStockin::where(['cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->whereIn('id', $ids)->count();

        if ($maininfocount != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '存在已审核商品']);
        }

        $infolist = GoodsStockinInfolist::where(['cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->whereIn('p_id', $ids)->get()->toArray();

        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                //增加逻辑 入库存列表，保证条码唯一
                $isexist = GoodsStockList::where(['cp_id' => $cp_id, 'goods_sn_code' => $info['goods_sn_code'], 'is_del' => 1])->first();
                if ($isexist) {
                    return response()->json(['code' => '001', 'msg' => '条码：' . $info['goods_sn_code'] . '存在重复']);
                }

                $id = $info['id'];
                GoodsStockinInfolist::where(['id' => $id, 'cp_id' => $cp_id, 'store_id' => $store_id])->update(['audit_status' => 2, 'audit_success_count' => $info['count'], 'audit_at' => time()]);
                //入库操作
                $data = $info;
                unset($data['id']);
                unset($data['p_id']);
                unset($data['audit_status']);
                unset($data['audit_at']);
                $data['piece_weight'] = $data['piece_weight_new'];
                $data['netglod_weight'] = $data['netglod_weight_new'];
                $data['label_price'] = $data['label_price_new'];
                $data['total_piece_weight'] = $data['total_piece_weight_new'];
                $data['total_netglod_weight'] = $data['total_netglod_weight_new'];
                $data['create_at'] = time();
                $data['start_stockin_store_id'] = $data['store_id'];
                GoodsStockList::create($data);
                $audit_status_count = GoodsStockinInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }
                GoodsStockin::where(['id' => $info['p_id'], 'cp_id' => $cp_id, 'store_id' => $store_id])->increment('audit_success_count', $info['count'], ['audit_status' => $audit_status, 'audit_at' => time()]);

                Goods::goodsLog($request, 0, intval($info['store_id']), $info, intval($info['count']), 1, $info['order_sncode']);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '入库单审核成功']);
    }


    /**
     * 撤审
     */
    public function doauditcancelmore(Request $request)
    {

        $id = intval($request->id);

        if ($id <= 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];


        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }
        $store_id = intval($accountinfo['store_ids']);
        $maininfo = GoodsStockin::where(['cp_id' => $cp_id, 'store_id' => $store_id])->where('id', $id)->first();

        if (!$maininfo) {
            return response()->json(['code' => '001', 'msg' => '数据不存在，不能操作']);
        }

        if ($maininfo->audit_status != 3) {
            return response()->json(['code' => '001', 'msg' => '审核成功后才能撤销审核']);
        }

        $list = GoodsStockinInfolist::query()
            ->where(['cp_id' => $cp_id, 'store_id' => $store_id, 'p_id' => $id])
            ->get()
            ->toArray();
        if (empty($list)) {
            return response()->json(['code' => '001', 'msg' => '数据不存在不能撤销审核']);
        }
        $auditArr = array_column($list, 'audit_status');
        if (in_array(1, $auditArr)) {
            return response()->json(['code' => '001', 'msg' => '存在未审核数据不可撤销审核']);
        }

        if (in_array(3, $auditArr)) {
            return response()->json(['code' => '001', 'msg' => '商品已取消，不可撤销审核']);
        }
        $goods_sn = array_column($list, 'goods_sn_code');

        $stockList = GoodsStockList::query()
            ->where(['cp_id' => $cp_id, 'store_id' => $store_id, 'is_del' => 1])
            ->whereIn('goods_sn_code', $goods_sn)
            ->get()
            ->toArray();

        $stock_sn = array_column($stockList, 'goods_sn_code');
        $update_at = array_filter(array_column($stockList, 'update_at'));

        if (!empty($update_at)) {
            return response()->json(['code' => '001', 'msg' => '商品已修改，不能撤审']);
        }

        if (array_diff($goods_sn, $stock_sn) != array_diff($stock_sn, $goods_sn)) {
            return response()->json(['code' => '001', 'msg' => '商品条码已修改或已删除，不能撤审']);
        }

        // 销售
        $stockIds = array_column($stockList, 'id');
        $salesCount = OrderSalesGoods::query()
            ->where(['cp_id' => $cp_id, 'store_id' => $store_id, 'is_del' => 1])
            ->whereIn('goods_stock_id', $stockIds)
            ->count();
        if ($salesCount > 0) {
            return response()->json(['code' => '001', 'msg' => '商品售出，不能撤审']);
        }


        // 调拨
        $allotCount = GoodsAllotInfolist::query()
            ->where(['cp_id' => $cp_id])
            ->whereIn('goods_sn_code', $goods_sn)
            ->count();
        if ($allotCount > 0) {
            return response()->json(['code' => '001', 'msg' => '商品已被调拨，不能撤审']);
        }

        //返厂
        $allotCount = GoodsReturnInfolist::query()
            ->where(['cp_id' => $cp_id, 'store_id' => $store_id])
            ->whereIn('goods_sn_code', $goods_sn)
            ->count();
        if ($allotCount > 0) {
            return response()->json(['code' => '001', 'msg' => '商品已被返厂，不能撤审']);
        }

        $oldCount = Stock::query()
            ->where(['cp_id' => $cp_id, 'store_id' => $store_id, 'is_del' => 1])
            ->whereIn('goods_sn_code', $goods_sn)
            ->count();
        if ($oldCount > 0) {
            return response()->json(['code' => '001', 'msg' => '商品已转旧料，不能撤审']);
        }


        DB::beginTransaction();
        try {
            foreach ($list as $info) {
                if ($info['audit_status'] == 2) {
                    //审核成功
                    GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $info['store_id'], 'goods_sn_code' => $info['goods_sn_code']])->update(['is_del' => 2, 'del_at' => time()]);
                    //流水
                    Goods::goodsLog($request, 0, intval($info['store_id']), $info, intval($info['count']), 5, $info['order_sncode']);
                }
                GoodsStockinInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'store_id' => $store_id, 'id' => $info['id']])->update(['audit_success_count' => 0, 'audit_failed_count' => 0, 'audit_status' => 1, 'audit_at' => time()]);
            }
            GoodsStockin::where(['cp_id' => $cp_id, 'store_id' => $store_id])->where('id', $id)->update(['audit_success_count' => 0, 'audit_failed_count' => 0, 'audit_status' => 1]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '撤销审核失败：' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '撤销审核成功']);
    }

    /**
     * 快速审核
     */
    public function doauditsuccessfast(Request $request)
    {
        $goods_sn_code_list = $request->goods_sn_code;

        $goods_sn_code_list = $goods_sn_code_list ? (is_array($goods_sn_code_list) ? $goods_sn_code_list : (explode(',', $goods_sn_code_list))) : [];
        if (count($goods_sn_code_list) <= 0) {
            return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['list' => []]]);
        }


        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];


        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }
        $store_id = intval($accountinfo['store_ids']);
        $return_msg = [];
        foreach ($goods_sn_code_list as $goods_sn_code) {
            $info = GoodsStockinInfolist::where(['goods_sn_code' => $goods_sn_code, 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->first();
            if (!$info) {
                $return_msg[] = '条码：' . $goods_sn_code . '无效';
                continue;
            }
            $info = $info->toArray();
            DB::beginTransaction();
            try {
                //增加逻辑 入库存列表，保证条码唯一
                $isexist = GoodsStockList::where(['cp_id' => $cp_id, 'goods_sn_code' => $info['goods_sn_code'], 'is_del' => 1])->first();
                if ($isexist) {
                    return response()->json(['code' => '001', 'msg' => '条码：' . $info['goods_sn_code'] . '存在重复']);
                }

                $id = $info['id'];
                GoodsStockinInfolist::where(['id' => $id, 'cp_id' => $cp_id, 'store_id' => $store_id])->update(['audit_status' => 2, 'audit_success_count' => $info['count'], 'audit_at' => time()]);
                //入库操作
                $data = $info;
                unset($data['id']);
                unset($data['p_id']);
                unset($data['audit_status']);
                unset($data['audit_at']);
                $data['piece_weight'] = $data['piece_weight_new'];
                $data['netglod_weight'] = $data['netglod_weight_new'];
                $data['label_price'] = $data['label_price_new'];
                $data['total_piece_weight'] = $data['total_piece_weight_new'];
                $data['total_netglod_weight'] = $data['total_netglod_weight_new'];
                $data['create_at'] = time();

                $data['start_stockin_store_id'] = $data['store_id'];
                GoodsStockList::create($data);
                $audit_status_count = GoodsStockinInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }
                GoodsStockin::where(['id' => $info['p_id'], 'cp_id' => $cp_id, 'store_id' => $store_id])->increment('audit_success_count', $info['count'], ['audit_status' => $audit_status, 'audit_at' => time()]);

                Goods::goodsLog($request, 0, intval($info['store_id']), $info, intval($info['count']), 1, $info['order_sncode']);

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '条码:' . $goods_sn_code . '审核失败' . $e->getMessage()]);
            }
        }


        return response()->json(['code' => '000', 'msg' => '入库单审核成功', 'data' => ['return_msg' => $return_msg]]);
    }


    /**
     * 审核取消
     */
    public function doauditcancel(Request $request)
    {

        $p_id = $request->p_id;
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        $goods_style_ids = $request->goods_style_ids;
        $goods_style_ids = is_array($goods_style_ids) ? $ids : (is_array(json_decode($goods_style_ids, true)) ? json_decode($goods_style_ids, true) : []);
        $goods_category_ids = $request->goods_category_ids;
        $goods_category_ids = is_array($goods_category_ids) ? $goods_category_ids : (is_array(json_decode($goods_category_ids, true)) ? json_decode($goods_category_ids, true) : []);

        if (count($ids) == 0 && count($goods_style_ids) == 0 && count($goods_category_ids) == 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }
        $maininfo = GoodsStockin::where(['id' => $p_id, 'cp_id' => $cp_id])->first();

        if (!$maininfo) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $store_id = intval($accountinfo['store_ids']);
        if (count($goods_category_ids) > 0) {
            $infolist = GoodsStockinInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->whereIn('goods_category_id', $goods_category_ids)->get()->toArray();
        } else {
            if (count($goods_style_ids) > 0) {
                $infolist = GoodsStockinInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->whereIn('goods_style_id', $goods_style_ids)->get()->toArray();
            } else {
                $infolist = GoodsStockinInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->whereIn('id', $ids)->get()->toArray();
            }
        }

        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                GoodsStockinInfolist::where(['id' => $id, 'cp_id' => $cp_id, 'store_id' => $store_id])->update(['audit_status' => 3, 'audit_failed_count' => $info['count'], 'audit_at' => time()]);
                $audit_status_count = GoodsStockinInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }
                GoodsStockin::where(['id' => $info['p_id'], 'cp_id' => $cp_id, 'store_id' => $store_id])->increment('audit_failed_count', $info['count'], ['audit_status' => $audit_status]);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核取消操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '入库单审核取消成功']);
    }


    /**
     * 审核取消
     */
    public function doauditmorecancel(Request $request)
    {

        $p_ids = $request->ids;
        $p_ids = is_array($p_ids) ? $p_ids : (is_array(json_decode($p_ids, true)) ? json_decode($p_ids, true) : []);


        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }
        $store_id = intval($accountinfo['store_ids']);

        $maininfo_arr = GoodsStockin::where(['cp_id' => $cp_id, 'store_id' => $store_id])->whereIn('audit_status', [1, 2])->whereIn('id', $p_ids)->first();

        if (count($maininfo_arr) != count($p_ids)) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $infolist = GoodsStockinInfolist::where(['cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])
            ->whereIn('p_id', $p_ids)->get()->toArray();

        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                GoodsStockinInfolist::where(['id' => $id, 'cp_id' => $cp_id, 'store_id' => $store_id])->update(['audit_status' => 3, 'audit_failed_count' => $info['count'], 'audit_at' => time()]);
                $audit_status_count = GoodsStockinInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }
                GoodsStockin::where(['id' => $info['p_id'], 'cp_id' => $cp_id, 'store_id' => $store_id])->increment('audit_failed_count', $info['count'], ['audit_status' => $audit_status, 'audit_at' => time()]);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核取消操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '入库单审核取消成功']);
    }

    /**
     * 计算标签价
     */


    /**
     * 模板下载
     */
    public function downdownload(Request $request)
    {
        $store_id = intval($request->store_id);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $cp_id])->first();
        if (!$storeinfo) {
            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }
        // 获取门店商品类别
        // $row = [[
        //     '商品类别（必填）', '供应商', '款式（必填）', '数量（必填）', '件销工费', '克销工费', '计算方式', //A-G
        //     '倍率（按件必填）', '件重（按件必填）', '金重（按克必填）', '成本金价（必填）', '件成本工费', '克成本工费', '是否一码多货（必填）', //HIJKLMN
        //     '总金重（一码多货必填）', '含量', '工艺', '圈号', '款号', '宝石费1', '宝石费2', '附加费1', '附加费2', '品牌', '证书号', 'GIA证书号', // O-Z
        //     '证书费', '主石重', '主石数', '副石重', '副石数', '颜色', '净度', //A-G
        //     '主石值', '副石值', '切工', '价格类型', '石料材质', '采购时间（20240101）', '支付方式', //HIJKLMN
        //     '应付账款', '备注'
        // ]];
        // $options = [
        //     'A' => GoodsCategory::where(['cp_id' => $cp_id, 'is_del' => 1, 'store_id' => $store_id])->pluck('category_name')->toArray(),
        //     'B' => Supply::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('supply_name')->toArray(),
        //     'C' => GoodsStyle::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('style_name')->toArray(),
        //     'G' => ['重量', '单件成本'],
        //     'N' => ['否', '是'],
        //     'Q' => GoodsCraft::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('craft_name')->toArray(),
        //     'X' => GoodsBrand::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('brand_name')->toArray(),
        //     'AK' => GoodsPricetype::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('pricetype_name')->toArray(),
        //     'AL' => GoodsStone::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('stone_name')->toArray(),
        //     'AN' => PaytypeList::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('paytype_name')->toArray(),
        // ];
        // $datawith = [
        //     'A' => '25', 'B' => '25', 'C' => '25', 'D' => '25', 'E' => '25', 'F' => '25', 'G' => '25',
        //     'H' => '25', 'I' => '25', 'J' => '25', 'K' => '25', 'L' => '25', 'M' => '25', 'N' => '25',
        //     'O' => '25', 'P' => '25', 'Q' => '25', 'R' => '25', 'S' => '25', 'T' => '25', 'U' => '25', 'V' => '25', 'W' => '25', 'X' => '25', 'Y' => '25', 'Z' => '25',
        //     'AA' => '25', 'AB' => '25', 'AC' => '25', 'AD' => '25', 'AE' => '25', 'AF' => '25', 'AG' => '25',
        //     'AH' => '25', 'AI' => '25', 'AJ' => '25', 'AK' => '25', 'AL' => '25', 'AM' => '25', 'AN' => '25',
        // ];


        $row = [[
            '供应商', '条码', '品名', '款式', '商品类别', '含量', '数量',//A-G
            '件重', '金重', '件销工费', '克销工费', '倍率', '成本金价', '件成本工费',//H-N
            '克成本工费', '计算方式', '标签价', '单件成本', '是否一码多货', '总金重',//O-T
            '工艺', '圈号', '款号', '宝石费1', '宝石费2', '附加费1',//U-Z

            '附加费2', '品牌', '证书号', 'GIA证书号', '证书费', '主石重', '副石重',//AA-AG
            '主石数', '副石数', '颜色', '净度', '主石值', '副石值', '切工', //AH-AN
            '价格类型', '石料材质', '库存时间', '支付方式', '应付账款', '备注'//AO-AT
        ]];
        $options = [
            'A' => Supply::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('supply_name')->toArray(),
            'D' => GoodsStyle::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('style_name')->toArray(),
            'E' => GoodsCategory::where(['cp_id' => $cp_id, 'is_del' => 1, 'store_id' => $store_id])->pluck('category_name')->toArray(),
            'F' => GoodsContent::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('content_name')->toArray(),
            'P' => ['重量', '单件成本'],
            'S' => ['否', '是'],
            'U' => GoodsCraft::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('craft_name')->toArray(),
            'AB' => GoodsBrand::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('brand_name')->toArray(),

            'AO' => GoodsPricetype::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('pricetype_name')->toArray(),
            'AP' => GoodsStone::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('stone_name')->toArray(),
            'AR' => PaytypeList::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('paytype_name')->toArray(),
        ];
        $datawith = [
            'A' => '25', 'B' => '25', 'C' => '25', 'D' => '25', 'E' => '25', 'F' => '25', 'G' => '25',
            'H' => '25', 'I' => '25', 'J' => '25', 'K' => '25', 'L' => '25', 'M' => '25', 'N' => '25',
            'O' => '25', 'P' => '25', 'Q' => '25', 'R' => '25', 'S' => '25', 'T' => '25', 'U' => '25', 'V' => '25', 'W' => '25', 'X' => '25', 'Y' => '25', 'Z' => '25',
            'AA' => '25', 'AB' => '25', 'AC' => '25', 'AD' => '25', 'AE' => '25', 'AF' => '25', 'AG' => '25',
            'AH' => '25', 'AI' => '25', 'AJ' => '25', 'AK' => '25', 'AL' => '25', 'AM' => '25', 'AN' => '25',
            'AO' => '25', 'AP' => '25', 'AQ' => '25', 'AR' => '25', 'AS' => '25', 'AT' => '25',
        ];
        $customColor = ['C', 'D', 'E', 'G'];

        $filename = '商品入库导入模板_' . time() . '.xlsx';
        return Excel::download(new DownloadTemp($row, $options, $datawith, $customColor), $filename);
    }

    /**
     * 入库批量调整
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function doimportnew(Request $request)
    {
        ini_set('memory_limit', '-1');
        $store_id = intval($request->store_id);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $cp_id])->first();
        if (!$storeinfo) {
            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }
        $remark = $request->remark ?? '';
        $filepathname = $request->filepathname;
        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {

            try {


                // $file = storage_path() . $filepathname;
                // $data = Excel::toArray(null, $file)[0];

                $config = ['path' => storage_path()];
                $excel = new \Vtiful\Kernel\Excel($config);

                $data = $excel->openFile($filepathname)
                    ->openSheet()
                    ->setType([
                        1 => \Vtiful\Kernel\Excel::TYPE_STRING,
                    ])
                    ->getSheetData();
                if (count($data) > 5001) {
                    return response()->json(['code' => '001', 'msg' => '超过导入数据上限,最多一次可以导入5000条']);
                }
                $total_count = 0;
                $ins_data = [];
                $return_msg = [];
                $error_msg = [];


                // 获取数组的第一行和最后一行
                $first = reset($data)[0] ?? '';
                $end = end($data)[0] ?? '';
                if (!empty($first) && $first == '库存实时明细') {
                    unset($data[0], $data[1]);
                }

                if (!empty($end) && $end == '合计') {
                    array_pop($data);
                }

                $data = array_values($data);

                // 获取表头并映射到列索引
                $header = array_filter(array_unique(array_shift($data)));
                $columnMap = array_flip($header);

                $requiredColumns = [
                    'goods_sn_code' => '条码',
                    'goods_name' => '品名',
                    'goods_style_id' => '款式',
                    'goods_category_id' => '商品类别',
                    'supply_id' => '供应商',
                    'count' => '数量',
                    'gramprice_fee' => '克销工费',
                    'label_price' => '标签价',
                    'pieceprice_fee' => '件销工费',
                    'piece_weight' => '件重',
                    'netglod_weight' => '金重',
                    'goods_content_id' => '含量',
                    'costglod_price' => '成本金价',
                    'costpiece_fee' => '件成本工费',
                    'costgram_fee' => '克成本工费',
                    'piececost_fee' => '单件成本',
                    'goods_craft_id' => '工艺',
                    'c_no' => '圈号',
                    's_no' => '款号',
                    'gemstone_fee1' => '宝石费1',
                    'gemstone_fee2' => '宝石费2',
                    'add_fee1' => '附加费1',
                    'add_fee2' => '附加费2',
                    'goods_brand_id' => '品牌',
                    'pricetype' => '计算方式',
                    'cf_no' => '证书号',
                    'cf_no_gia' => 'GIA证书号',
                    'cf_fee' => '证书费',
                    'main_stone_weigth' => '主石重',
                    'main_stone_count' => '主石数',
                    'other_stone_weigth' => '副石重',
                    'other_stone_count' => '副石数',
                    'color' => '颜色',
                    'clarity' => '净度',
                    'main_stone_val' => '主石值',
                    'other_stone_val' => '副石值',
                    'cut' => '切工',
                    'goods_pricetype_id' => '价格类型',
                    'goods_stone_id' => '石料材质',
                    'procure_at' => '库存时间',
                    'paytype_id' => '支付方式',
                    'paymoney' => '应付账款',
                    'remark' => '备注',
                    'total_netglod_weight' => '总金重',
                    'odds' => '倍率',
                    'is_code_more' => '是否一码多货'
                ];


                $dataMap = [];
                // 检查必需的列是否存在
                foreach ($requiredColumns as $field => $col) {
                    $key = $columnMap[$col] ?? '';
                    if ($key !== '') {
                        $dataMap[$key] = $field;
                    }

                }


                if (empty($data)) {
                    return response()->json(['code' => '001', 'msg' => '导入的数据不能为空']);
                }

                $order_sncode = StoreCommon::createOrderSn();

                $categoryArr = GoodsCategory::query()
                    ->where(['cp_id' => $cp_id, 'store_id' => $store_id, 'is_del' => 1])
                    ->get()
                    ->pluck(null, 'category_name')
                    ->toArray();
                $styleArr = GoodsStyle::query()
                    ->where(['cp_id' => $cp_id, 'is_del' => 1])
                    ->get()
                    ->pluck(null, 'style_name')
                    ->toArray();

                $supplyArr = Supply::query()
                    ->where(['cp_id' => $cp_id, 'is_del' => 1])
                    ->get()
                    ->pluck(null, 'supply_name')
                    ->toArray();

                $contentArr = GoodsContent::query()
                    ->where(['cp_id' => $cp_id, 'is_del' => 1])
                    ->get()
                    ->pluck(null, 'content_name')
                    ->toArray();
                $dataNew = [];
                foreach ($data as $value) {
                    $val = [];
                    foreach ($value as $k => $v) {
                        $kk = $dataMap[$k] ?? '';
                        $val[$kk] = $v;
                    }
                    $dataNew[] = $val;
                }


                foreach ($dataNew as $nk => &$nv) {
                    $nv['goods_sn_code'] = !empty($nv['goods_sn_code']) ? $nv['goods_sn_code'] : (int)(date('ymdhis') + $nk);
                }


                // 获取条码
                $goods_sn = array_column($dataNew, 'goods_sn_code');
                $duplicates = Common::duplicatesArray($goods_sn);

                if (!empty($duplicates)) {
                    return response()->json(['code' => '001', 'msg' => '导入的数据条码有重复:' . implode(',', $duplicates)]);
                }

                if (count($goods_sn) != count(array_unique($goods_sn))) {
                    return response()->json(['code' => '001', 'msg' => '导入的表格数据有重复']);
                }
                $error_msg = $this->checkInGoods($cp_id, $goods_sn);
                if (!empty($error_msg)) {
                    $err = implode(',', $error_msg);
                    return response()->json(['code' => '001', 'msg' => $err]);
                }

                foreach ($dataNew as $key => $val) {
                    if (empty($val['goods_name'])) {
                        return response()->json(['code' => '001', 'msg' => '第' . ($key + 2) . '行,导入数据含品名不能为空']);
                    }
                    if (empty($val['goods_category_id'])) {
                        return response()->json(['code' => '001', 'msg' => '第' . ($key + 2) . '行,导入数据商品类别不能为空']);
                    }
                    if ((empty($val['count']) || $val['count'] < 0)) {
                        return response()->json(['code' => '001', 'msg' => '第' . ($key + 2) . '行,导入数据数量不能为空或数量小于0']);
                    }
                    if (empty($val['goods_style_id'])) {
                        return response()->json(['code' => '001', 'msg' => '第' . ($key + 2) . '行,导入数据款式不能为空']);
                    }


                    $category = $categoryArr[trim($val['goods_category_id'])] ?? [];
                    $style = $styleArr[$val['goods_style_id']] ?? [];

                    $supply = (isset($val['supply_id']) && $val['supply_id'] > 0) ? ($supplyArr[$val['supply_id']] ?? []) : [];
                    $content = (isset($val['goods_content_id']) && $val['goods_content_id'] > 0) ? ($contentArr[$val['goods_content_id']] ?? []) : [];

                    $goods_category_id = $category['id'] ?? 0;
                    $is_gram = $category['is_gram'] ?? 0;
                    if (empty($goods_category_id)) {
                        return response()->json(['code' => '001', 'msg' => '第' . ($key + 2) . '行,导入的商品类别查询不到']);
                    }

                    $style_id = $style['id'] ?? 0;

                    if (empty($style_id)) {
                        return response()->json(['code' => '001', 'msg' => '第' . ($key + 2) . '行,导入的款式查询不到']);
                    }


                    $label_price = (isset($val['label_price']) && doubleval($val['label_price']) > 0) ? intval($val['label_price'] * 100) : 0;//标签价
                    $piece_weight = (isset($val['piece_weight']) && doubleval($val['piece_weight']) > 0) ? doubleval($val['piece_weight']) : 0;
                    $netglod_weight = (isset($val['netglod_weight']) && doubleval($val['netglod_weight']) > 0) ? doubleval($val['netglod_weight']) : 0;//金重
                    $total_netglod_weight = (isset($val['total_netglod_weight']) && doubleval($val['total_netglod_weight']) > 0) ? doubleval($val['total_netglod_weight']) : 0; //总金重
                    $is_code_more = (isset($val['is_code_more']) && strval($val['is_code_more']) == '是') ? 2 : 1;//是否一码多货
                    $pricetype = (isset($val['pricetype']) && strval($val['pricetype']) == '单件成本') ? 1 : ((isset($val['pricetype']) && strval($val['pricetype']) == '重量') ? 2 : 0);
                    //克成本工费
                    $costgram_fee = empty($val['costgram_fee']) ? 0 : ($val['costgram_fee'] ?? 0);
                    //件成本工费
                    $costpiece_fee = empty($val['costpiece_fee']) ? 0 : ($val['costpiece_fee'] ?? 0);
                    $total_piece_weight = 0;
                    $total_cost_fee = 0;
                    $piececost_fee = empty($val['piececost_fee']) ? 0 : ($val['piececost_fee'] ?? 0);
                    // 成本金价
                    $costglod_price = empty($val['costglod_price']) ? 0 : ($val['costglod_price'] ?? 0);


                    if ($is_code_more == 2) {
                        if ($total_netglod_weight <= 0) {
                            $error_msg[] = '第' . ($key + 2) . '行,一码多货商品总金重必填';
                        } else {
                            //是一码多货的商品的 总成本=成本金价*总金重
                            $total_cost_fee = $costglod_price * $total_netglod_weight;
                        }

                    } else {
                        // 非一码多货，总金重 =金重*数量
                        $total_netglod_weight = $netglod_weight * (int)($val['count'] ?? 0);
                        //非一码多货，总件重 =件重*数量
                        $total_piece_weight = $piece_weight * (int)($val['count'] ?? 0);

                        if ($is_gram == 1) {
                            //类别是素金和是克算
                            //总成本 = （成本金价*总金重+克成本工费*总金重）+件成本工费*数量
                            $total_cost_fee = ($costglod_price * $total_netglod_weight + $costgram_fee * $total_netglod_weight) + $costpiece_fee * ($val['count'] ?? 0);
                        } else {
                            if ($piececost_fee <= 0) {
                                //按克成本工费:单件成本=(成本金价+克成本工费)*件重
                                $canFee = $costgram_fee > 0 ? bcmul(($costgram_fee + $costglod_price), $piece_weight, 2) : 0;
                                // 按件成本工费(默认):单件成本=成本金价*件重+件成本工费
                                $pieceFee = $costpiece_fee > 0 ? bcadd($piece_weight * $costglod_price, $costpiece_fee, 2) : 0;

                                if ($costgram_fee > 0 && $costpiece_fee > 0) {
                                    $piececost_fee = $pieceFee;
                                } else {
                                    $piececost_fee = $canFee > 0 ? $canFee : $pieceFee;
                                }
                            }
                            if ($label_price <= 0) {
                                //1单件成本、2重量
                                if ($pricetype == 1) {
                                    //标签价
                                    $label_price = (bcmul($piececost_fee, (int)($val['odds'] ?? 1), 2)) * 100;

                                } elseif ($pricetype == 2) {
                                    //标签价=件重*倍率（倍率手动输入）
                                    $label_price = bcmul($piece_weight * (int)($val['odds'] ?? 1), 100);
                                }
                            }
                            //总成本 = 单件成本*数量
                            $total_cost_fee = ($piececost_fee * (int)($val['count'] ?? 0));
                        }
                    }


                    $item = [
                        'cp_id' => $cp_id,
                        'store_id' => $store_id,
                        'order_sncode' => $order_sncode,
                        'goods_sn_code' => (isset($val['goods_sn_code']) && !empty($val['goods_sn_code'])) ? $val['goods_sn_code'] : (int)(date('ymdhis') + $key),
                        'goods_name' => $val['goods_name'] ?? '',
                        'goods_style_id' => $style_id,
                        'goods_category_id' => $goods_category_id,
                        'stockin_at' => time(),
                        'supply_id' => $supply['id'] ?? 0,
                        'count' => $val['count'] ?? 0,
                        'gramprice_fee' => (isset($val['gramprice_fee']) && doubleval($val['gramprice_fee']) > 0) ? intval($val['gramprice_fee'] * 100) : 0, //克销工费
                        'label_price' => $label_price,
                        'pieceprice_fee' => (isset($val['pieceprice_fee']) && doubleval($val['pieceprice_fee']) > 0) ? intval($val['pieceprice_fee'] * 100) : 0, //件销工费
                        'piece_weight' => $piece_weight,
                        'netglod_weight' => $netglod_weight,
                        'goods_content_id' => $content['id'] ?? 0,
                        'costglod_price' => intval($costglod_price * 100), //成本金价
                        'costpiece_fee' => (isset($val['costpiece_fee']) && doubleval($val['costpiece_fee']) > 0) ? intval($val['costpiece_fee'] * 100) : 0, //件成本工费
                        'costgram_fee' => (isset($val['costgram_fee']) && doubleval($val['costgram_fee']) > 0) ? intval($val['costgram_fee'] * 100) : 0, //克成本工费
                        'piececost_fee' => (int)bcmul($piececost_fee, 100),
                        'goods_craft_id' => (isset($val['goods_craft_id']) && !empty($val['goods_craft_id'])) ? intval(GoodsCraft::where(['cp_id' => $cp_id, 'is_del' => 1, 'craft_name' => $val['goods_craft_id']])->value('id')) : 0, //工艺
                        'c_no' => !empty($val['c_no']) ? strval($val['c_no']) : '', //圈号
                        's_no' => !empty($val['s_no']) ? strval($val['s_no']) : '', //款号
                        'gemstone_fee1' => (isset($val['gemstone_fee1']) && doubleval($val['gemstone_fee1']) > 0) ? intval($val['gemstone_fee1'] * 100) : 0,  //宝石费1
                        'gemstone_fee2' => (isset($val['gemstone_fee2']) && doubleval($val['gemstone_fee2']) > 0) ? intval($val['gemstone_fee2'] * 100) : 0,  //宝石费2
                        'add_fee1' => (isset($val['add_fee1']) && doubleval($val['add_fee1']) > 0) ? intval($val['add_fee1'] * 100) : 0, //附加费1
                        'add_fee2' => (isset($val['add_fee2']) && doubleval($val['add_fee2']) > 0) ? intval($val['add_fee2'] * 100) : 0, //附加费2
                        'goods_brand_id' => (isset($val['goods_brand_id']) && !empty($val['goods_brand_id'])) ? intval(GoodsBrand::where(['cp_id' => $cp_id, 'is_del' => 1, 'brand_name' => $val['goods_brand_id']])->value('id')) : 0, //品牌
                        'pricetype' => $pricetype,
                        'cf_no' => !empty($val['cf_no']) ? strval($val['cf_no']) : '', //证书号
                        'cf_no_gia' => !empty($val['cf_no_gia']) ? strval($val['cf_no_gia']) : '', //GIA证书号
                        'cf_fee' => (isset($val['cf_fee']) && doubleval($val['cf_fee']) > 0) ? intval($val['cf_fee'] * 100) : 0, //证书费
                        'main_stone_weigth' => (isset($val['main_stone_weigth']) && doubleval($val['main_stone_weigth']) > 0) ? doubleval($val['main_stone_weigth']) : 0, //主石重
                        'main_stone_count' => (isset($val['main_stone_weigth']) && intval($val['main_stone_weigth']) > 0) ? intval($val['main_stone_weigth']) : 0, //主石数
                        'other_stone_weigth' => (isset($val['other_stone_weigth']) && doubleval($val['other_stone_weigth']) > 0) ? doubleval($val['other_stone_weigth']) : 0, //副石重
                        'other_stone_count' => (isset($val['other_stone_weigth']) && intval($val['other_stone_weigth']) > 0) ? intval($val['other_stone_weigth']) : 0, //副石数
                        'color' => !empty($val['color']) ? strval($val['color']) : '', //颜色
                        'clarity' => !empty($val['clarity']) ? strval($val['clarity']) : '', //净度
                        'main_stone_val' => !empty($val['main_stone_val']) ? strval($val['main_stone_val']) : '', //主石值
                        'other_stone_val' => !empty($val['other_stone_val']) ? strval($val['other_stone_val']) : '', //副石值
                        'cut' => !empty($val['cut']) ? strval($val['cut']) : '', //切工
                        'goods_pricetype_id' => (isset($val['goods_pricetype_id']) && !empty($val['goods_pricetype_id'])) ? intval(GoodsPricetype::where(['cp_id' => $cp_id, 'is_del' => 1, 'pricetype_name' => $val['goods_pricetype_id']])->value('id')) : 0, //价格类型
                        'goods_stone_id' => (isset($val['goods_stone_id']) && !empty($val['goods_stone_id'])) ? intval(GoodsStone::where(['cp_id' => $cp_id, 'is_del' => 1, 'stone_name' => $val['goods_stone_id']])->value('id')) : 0, //石料材质
                        'procure_at' => (isset($val['procure_at']) && strtotime($val['procure_at']) > 0) ? strtotime($val['procure_at']) : 0, //采购时间
                        'paytype_id' => (isset($val['paytype_id']) && !empty($val['paytype_id'])) ? intval(PaytypeList::where(['cp_id' => $cp_id, 'is_del' => 1, 'paytype_name' => $val['paytype_id']])->value('id')) : 0, //支付方式
                        'paymoney' => (isset($val['paymoney']) && doubleval($val['paymoney']) > 0) ? intval($val['paymoney'] * 100) : 0, //应付账款
                        'remark' => !empty($val['remark']) ? strval($val['remark']) : '', //备注
                        'total_netglod_weight' => $total_netglod_weight,
                        'odds' => sprintf("%.2f", (isset($val['odds']) ? $val['odds'] : 1)),
                        'is_code_more' => $is_code_more
                    ];

                   // print_r($item);exit;

                    foreach ($item as $k => $v) {
                        if (!in_array($k, $dataMap) && !in_array($k, ['cp_id', 'store_id', 'order_sncode', 'stockin_at', 'is_code_more', 'piece_weight', 'netglod_weight', 'goods_category_id', 'goods_style_id'])) {
                            unset($item[$k]);
                        }
                    }

                    $item['label_price_new'] = $item['label_price'];
                    $item['piece_weight_new'] = $item['piece_weight'];
                    $item['netglod_weight_new'] = $item['netglod_weight'];
                    $item['total_netglod_weight_new'] = $total_netglod_weight;
                    $item['total_piece_weight'] = $total_piece_weight ?? 0;
                    $item['total_piece_weight_new'] = $total_piece_weight ?? 0;
                    $item['total_cost_fee'] = bcmul(($total_cost_fee ?? 0), 100);



                    if ($item['goods_sn_code'] == '') {
                        $item['goods_sn_code'] = (date('Y') - 2000) . date('mdHis', (time() + $key));
                    }

//                $isRepeatRes = $this->isRepeatGoodsSnCode(['goods_sn_code' => $item['goods_sn_code'], 'cp_id' => $cp_id]);
//                //商品入库只检查 库存列表条码
//                if ($isRepeatRes['code'] == '001') {
//                    $error_msg[] = '第' . ($key + 1) . '行,' . $isRepeatRes['msg'];
//                    continue;
//                }
                    $total_count += $item['count'];

                    $return_msg[] = '导入成功：条码' . $item['goods_sn_code'] . '成功导入';
                    $ins_data[] = $item;
                }


                if (!empty($error_msg)) {
                    $err = implode(',', $error_msg);
                    return response()->json(['code' => '001', 'msg' => "导入的数据报错:" . $err]);
                }

                $maindata = [];
                $maindata['cp_id'] = $cp_id;
                $maindata['order_sncode'] = $order_sncode;
                $maindata['goods_count'] = $total_count;
                $maindata['supply_id'] = $ins_data[0]['supply_id'] ?? 0;
                $maindata['goods_brand_id'] = $ins_data[0]['goods_brand_id'];
                $maindata['paymoney'] = array_sum(array_column($ins_data, 'paymoney'));
                $maindata['store_id'] = $store_id;
                $maindata['create_at'] = time();
                $maindata['update_at'] = time();
                $maindata['remark'] = $remark;
                $maindata['create_account_id'] = $accountinfo['id'];
                $maindata['create_account_real_name'] = $accountinfo['real_name'];

                DB::beginTransaction();
                try {
                    $pid = GoodsStockin::create($maindata)->id;
                    foreach ($ins_data as &$val) {
                        $val['p_id'] = $pid;
                    }
                    $batches = array_chunk($ins_data, 1000);
                    foreach ($batches as $batch) {
                        GoodsStockinInfolist::query()->insert($batch);
                    }


                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    return response()->json(['code' => '001', 'msg' => '商品入库导入失败' . $e->getLine() . $e->getMessage()]);
                }
                return response()->json(['code' => '000', 'msg' => '商品入库导入成功', 'data' => ['return_msg' => $return_msg, 'error_msg' => $error_msg]]);

            } catch (\Exception $e) {

                info('商品入库导入失败'.$e->getLine() . $e->getMessage());
                return response()->json(['code' => '001', 'msg' => '导入数据模版错误']);
            }
        } else {
            return response()->json(['code' => '001', 'msg' => '文件不存在'], 200);
        }
    }


    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        $list = GoodsStockinInfolist::getList($request)['list'];
        $row = [
            ['start_sotre' => '商品入库列表'],
            [
                'startstore' => '起始门店',
                'targetstore' => '目标门店',
                'stockin_at' => '入库日期',
                'supply_name' => '供应商',
                'style_name' => '款式',
                'goods_sn_code' => '条码',
                'goods_name' => '品名',
                'category_name' => '商品类别',
                'count' => '数量',
                'gramprice_fee' => '克销工费',
                'label_price' => '标签价',
                'pieceprice_fee' => '件销工费',
                'piece_weight' => '件重',
                'netglod_weight' => '金重',
                'total_weight' => '总重量',
                'total_stock_weight' => '入库总重量',
                'content' => '含量',
                'costglod_price' => '成本金价',
                'costpiece_fee' => '件成本工费',
                'costgram_fee' => '克成本工费',
                'piececost_fee' => '单件成本',
                'goods_craft_name' => '工艺',
                'c_no' => '圈号',
                's_no' => '款号',
                'gemstone_fee1' => '宝石费1',
                'gemstone_fee2' => '宝石费2',
                'add_fee1' => '附加费1',
                'add_fee2' => '附加费2',
                'brand_name' => '品牌',
                'cf_no' => '证书号', //Z
                'cf_no_gia' => 'GIA证书号',
                'cf_fee' => '证书费',
                'main_stone_weigth' => '主石重',
                'main_stone_count' => '主石数',
                'other_stone_weigth' => '副石重',
                'other_stone_count' => '副石数',
                'color' => '颜色',
                'clarity' => '净度',
                'main_stone_val' => '主石值',
                'other_stone_val' => '副石值',
                'cut' => '切工',
                'goods_pricetype_name' => '价格类型',
                'goods_stone_name' => '石料材质',
                'audit_at' => '库存时间',
                'paytype_name' => '支付方式',
                'paymoney' => '应付账款',
                'is_code_more' => '一码多货',
                'remark' => '备注',
                'audit_status' => '审核状态'
            ]];

        $is_store_account = StoreCommon::getIsStoreAccount($request);
        if (!$is_store_account) {
            unset($row[0]['supply_name']);
            unset($row[0]['paymoney']);
            unset($row[0]['costglod_price']);
            unset($row[0]['total_fee']);
            unset($row[0]['piececost_fee']);
            unset($row[0]['piececost_fee_total']);
        }

        $exceldata = [];
        foreach ($list as $val) {
            $goods_category = $val['goods_category'] ?? [];
            $exceldata[] = [
                'startstore' => '财务部',
                'targetstore' => $val['storeinfo']['store_name'],
                'stockin_at' => date('Y-m-d', $val['stockin_at']),
                'supply_name' => isset($val['supply']['supply_name']) ? $val['supply']['supply_name'] : '',
                'style_name' => $val['goods_style']['style_name'],
                'goods_sn_code' => $val['goods_sn_code'],
                'goods_name' => $val['goods_name'],
                'category_name' => $goods_category['category_name'] ?? '',
                'count' => $val['count'],
                'gramprice_fee' => $val['gramprice_fee'] / 100,
                'label_price' => $val['label_price_new'] / 100,
                'pieceprice_fee' => $val['pieceprice_fee'] / 100,
                'piece_weight' => $val['piece_weight_new'],
                'netglod_weight' => $val['netglod_weight_new'],
                'total_weight' => ($goods_category['is_gram'] ?? 0) > 0 ? ($goods_category['is_gram'] == 1 ? $val['total_netglod_weight_new'] : $val['total_piece_weight_new']) : '',
                'total_stock_weight' => ($goods_category['is_gram'] ?? 0) > 0 ? ($goods_category['is_gram'] == 1 ? $val['total_netglod_weight'] : $val['total_piece_weight']) : '',
                'content' => isset($val['goods_content']['content_name']) ? $val['goods_content']['content_name'] : '',
                'costglod_price' => $val['costglod_price'] / 100,
                'costpiece_fee' => $val['costpiece_fee'] / 100,
                'costgram_fee' => $val['costgram_fee'] / 100,
                'piececost_fee' => $val['piececost_fee'] / 100,
                'goods_craft_name' => isset($val['goods_craft']['craft_name']) ? $val['goods_craft']['craft_name'] : '',
                'c_no' => $val['c_no'],
                's_no' => $val['s_no'],
                'gemstone_fee1' => $val['gemstone_fee1'] / 100,
                'gemstone_fee2' => $val['gemstone_fee2'] / 100,
                'add_fee1' => $val['add_fee1'] / 100,
                'add_fee2' => $val['add_fee2'] / 100,
                'brand_name' => isset($val['goods_brand']['brand_name']) ? $val['goods_brand']['brand_name'] : '',
                'cf_no' => $val['cf_no'],
                'cf_no_gia' => $val['cf_no_gia'],
                'cf_fee' => $val['cf_fee'] / 100,
                'main_stone_weigth' => $val['main_stone_weigth'],
                'main_stone_count' => $val['main_stone_count'],
                'other_stone_weigth' => $val['other_stone_weigth'],
                'other_stone_count' => $val['other_stone_count'],
                'color' => $val['color'],
                'clarity' => $val['clarity'],
                'main_stone_val' => $val['main_stone_val'],
                'other_stone_val' => $val['other_stone_val'],
                'cut' => $val['cut'],
                'goods_pricetype_name' => isset($val['goods_pricetype']['goods_pricetype_name']) ? $val['goods_pricetype']['goods_pricetype_name'] : '',
                'goods_stone_name' => isset($val['goods_stone']['goods_stone_name']) ? $val['goods_stone']['goods_stone_name'] : '',
                'audit_at' => $val['procure_at'] > 0 ? date('Y-m-d H:i:s', $val['procure_at']) : ($val['audit_at'] > 0 ? date('Y-m-d H:i:s', $val['audit_at']) : ''),
                'paytype_name' => isset($val['paytype']['paytype_name']) ? $val['paytype']['paytype_name'] : '',
                'paymoney' => $val['paymoney'] / 100,
                'is_code_more' => $val['is_code_more'] == 1 ? '否' : '是',
                'remark' => $val['remark'],
                'audit_status' => $val['audit_status'] == 1 ? '待审核' : ($val['audit_status'] == 2 ? '审核' : '取消'),
            ];
        }

        $filename = '商品入库信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }


    public function doexportgoodsstockin(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $type = $request->type ?? 1;
        $info = GoodsStockin::with(['storeinfo'])->where(['id' => $id, 'cp_id' => $cp_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $where = [];
        $order_sncode = $request->order_sncode;
        if ($order_sncode != '') {
            $where[] = ['order_sncode', 'like', '%' . $order_sncode . '%'];
        }

        $goods_style_id = intval($request->goods_style_id);
        if ($goods_style_id > 0) {
            $where[] = ['goods_style_id', $goods_style_id];
        }

        $goods_category_id = intval($request->goods_category_id);
        if ($goods_category_id > 0) {
            $where[] = ['goods_category_id', $goods_category_id];
        }

        $audit_status = intval($request->audit_status);
        // if ($audit_status > 0) {
        //     $where[] = ['audit_status', $audit_status];
        // }

        if ($type == 1) {
            //获取分类查询信息
            $list1 = GoodsStockinInfolist::with(['goods_category'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where)
                ->groupBy('goods_category_id')
                ->select('goods_category_id', DB::raw('sum(count) as count,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(label_price*count) as label_price,sum(label_price_new*count) as label_price_new,sum(total_netglod_weight) as netglod_weight,sum(total_netglod_weight_new) as netglod_weight_new,sum(total_piece_weight) as piece_weight,sum(total_piece_weight_new) as piece_weight_new,sum(total_cost_fee) as total_price'))
                ->get()->toArray();

            $row = [
                ['table_header' => '入库汇总'],
                [
                    'audit_status' => '状态',
                    'category_name' => '入库类别',
                    'category_name1' => '商品类别',
                    'goods_style' => '款式',
                    'count' => '数量',
                    'allotcount' => '调拨数量',
                    'audit_count' => '已审数量',
                    'not_audit_count' => '未审数量',
                    'audit_failed_count' => '驳回数量',
                    'label_price' => '入库标签价',
                    'label_price_new' => '标签价',
                    'total_netglod_weight' => '入库总金重',
                    'total_netglod_weight_new' => '总金重',
                    'total_piece_weight' => '入库总件重',
                    'total_piece_weight_new' => '总件重',
                    'total_price' => '总成本',
                ]];

            $exceldata = [];
            foreach ($list1 as $k => $val) {


                if ($val['audit_failed_count'] + $val['audit_success_count'] >= $val['count']) {
                    $status = 3;
                } elseif ($val['audit_failed_count'] + $val['audit_success_count'] < $val['count']) {
                    if ($val['audit_failed_count'] == 0 && $val['audit_success_count'] == 0) {
                        $status = 1;
                    } else {
                        $status = 2;
                    }
                }
                $list1[$k]['audit_status'] = $status;

                if ($audit_status > 0) {
                    if ($status != $audit_status) {
                        continue;
                    }
                }

                $exceldata[] = [
                    'audit_status' => $val['audit_success_count'] == 0 && $val['audit_failed_count'] == 0 ? '待审核' : (($val['audit_success_count'] + $val['audit_failed_count']) == $val['count'] ? '审核' : '审核中'),
                    'category_name' => $val['goods_category']['category_name'],
                    'category_name1' => $val['goods_category']['category_name'],
                    'goods_style' => '--',
                    'count' => $val['count'],
                    'allotcount' => '--',
                    'audit_count' => ($val['audit_success_count'] + $val['audit_failed_count']),
                    'not_audit_count' => $val['count'] - ($val['audit_success_count'] + $val['audit_failed_count']),
                    'audit_failed_count' => $val['audit_failed_count'],
                    'label_price' => $val['label_price'] / 100,
                    'label_price_new' => $val['label_price_new'] / 100,
                    'total_netglod_weight' => $val['netglod_weight'],
                    'total_netglod_weight_new' => $val['netglod_weight_new'],
                    'total_piece_weight' => $val['piece_weight'],
                    'total_piece_weight_new' => $val['piece_weight_new'],
                    'total_price' => $val['total_price'] / 100,
                ];
            }
        } else {
            //按照款式汇总
            $list2 = GoodsStockinInfolist::with(['goods_style'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where)
                ->groupBy('goods_style_id')
                ->select('goods_style_id', DB::raw('sum(count) as count,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(label_price*count) as label_price,sum(label_price_new*count) as label_price_new,sum(total_netglod_weight) as netglod_weight,sum(total_netglod_weight_new) as netglod_weight_new,sum(total_piece_weight) as piece_weight,sum(total_piece_weight_new) as piece_weight_new,sum(total_cost_fee) as total_price'))
                ->get()->toArray();

            $row = [
                ['start_store' => '按照款式汇总'],
                [
                    'audit_status' => '状态',
                    'goods_style' => '款式',
                    'category_name' => '入库类别',
                    'category_name1' => '商品类别',
                    'count' => '数量',
                    'allotcount' => '调拨数量',
                    'audit_count' => '已审数量',
                    'not_audit_count' => '未审数量',
                    'audit_failed_count' => '驳回数量',
                    'label_price' => '入库标签价',
                    'label_price_new' => '标签价',
                    'total_netglod_weight' => '入库总金重',
                    'total_netglod_weight_new' => '总金重',
                    'total_piece_weight' => '入库总件重',
                    'total_piece_weight_new' => '总件重',
                    'total_price' => '总成本',
                ]];

            $exceldata = [];
            foreach ($list2 as $k => $val) {

                if ($val['audit_failed_count'] + $val['audit_success_count'] >= $val['count']) {
                    $status = 3;
                } elseif ($val['audit_failed_count'] + $val['audit_success_count'] < $val['count']) {
                    if ($val['audit_failed_count'] == 0 && $val['audit_success_count'] == 0) {
                        $status = 1;
                    } else {
                        $status = 2;
                    }
                }
                $list2[$k]['audit_status'] = $status;

                if ($audit_status > 0) {
                    if ($status != $audit_status) {
                        continue;
                    }
                }
                $exceldata[] = [
                    'audit_status' => $val['audit_success_count'] == 0 && $val['audit_failed_count'] == 0 ? '待审核' : (($val['audit_success_count'] + $val['audit_failed_count']) == $val['count'] ? '审核' : '审核中'),
                    'goods_style' => $val['goods_style'] ? $val['goods_style']['style_name'] : '--',
                    'category_name' => '--',
                    'category_name1' => '--',
                    'count' => $val['count'],
                    'allotcount' => '--',
                    'audit_count' => ($val['audit_success_count'] + $val['audit_failed_count']),
                    'not_audit_count' => $val['count'] - ($val['audit_success_count'] + $val['audit_failed_count']),
                    'audit_failed_count' => $val['audit_failed_count'],
                    'label_price' => $val['label_price'] / 100,
                    'label_price_new' => $val['label_price_new'] / 100,
                    'total_netglod_weight' => $val['netglod_weight'],
                    'total_netglod_weight_new' => $val['netglod_weight_new'],
                    'total_piece_weight' => $val['piece_weight'],
                    'total_piece_weight_new' => $val['piece_weight_new'],
                    'total_price' => $val['total_price'] / 100,
                ];
            }
        }


        $is_store_account = StoreCommon::getIsStoreAccount($request);
        if (!$is_store_account) {
            unset($row[0]['total_price']);
        }
        $filename = '商品入库明细信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);


    }

    public function dopaymoeny(Request $request)
    {
        $paymoney = intval($request->paymoney_new);
        $subject_id = intval($request->subject_id);
        $pay_type_id = intval($request->pay_type_id);
        $id = intval($request->id);

        if ($id <= 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $maininfo = GoodsStockin::where(['cp_id' => $cp_id])->where('id', $id)->first();
        if (!$maininfo) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($paymoney == 0 || $subject_id == 0 || $pay_type_id == '') {
            return response()->json(['code' => '001', 'msg' => '请保存表单完整']);
        }

        if (($maininfo->paymoney - $maininfo->paymoney_payed) < $paymoney) {

            return response()->json(['code' => '001', 'msg' => '付款金额不能大于未付款金额']);
        }

        $data = [
            'cp_id' => $cp_id,
            'store_id' => $maininfo->store_id,
            'stockin_id' => $maininfo->id,
            'subject_id' => $subject_id,
            'pay_type_id' => $pay_type_id,
            'paymoney' => $paymoney,
            'create_at' => time(),
            'update_at' => time(),
            'remark' => strval($request->remark),
        ];
        DB::beginTransaction();
        try {
            GoodsStockinPaymoneylog::create($data);
            Financial::createMoneyLogByPaymoney($cp_id, $data['store_id'], $data['pay_type_id'], $paymoney, '', $data['subject_id']);
            GoodsStockin::where(['cp_id' => $cp_id])->where('id', $id)->increment('paymoney_payed', $paymoney);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '付款操作失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 入库商品删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function stockDel(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
        ], [
            'id.required' => 'ID必填',
        ]);
        if ($validator->fails()) {
            $msg = $validator->errors()->first();
            return response()->json(['code' => '001', 'msg' => $msg]);
        }
        $params = $validator->validated();

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $stock = GoodsStockin::query()
            ->where('id', $params['id'])
            ->where('cp_id', $cp_id)
            ->first();
        if (empty($stock)) {
            return response()->json(['code' => '001', 'msg' => '数据不存在无法删除']);
        }

        $stock = $stock->toArray();

        if ($stock['audit_status'] != 1) {
            return response()->json(['code' => '001', 'msg' => '非待审核的数据不能删除']);
        }

        DB::beginTransaction();
        try {
            GoodsStockin::query()
                ->where('id', $params['id'])
                ->where('cp_id', $cp_id)
                ->delete();
            GoodsStockinInfolist::query()
                ->where('p_id', $params['id'])
                ->where('cp_id', $cp_id)
                ->delete();
            DB::commit();
            return response()->json(['code' => '000', 'msg' => '删除成功']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '删除商品失败' . $e->getMessage()]);
        }

    }

    /**
     *   判定条码是否重复
     *   1. 未审核数据，条码存在入库表，不可入库
     *   2. 未审核数据，删除后，可重新入库
     *   3. 已审核数据，库存表未删除，不可入库
     *   4. 已审核数据，删除库存表，可以入库
     *
     *   params  string goods_sn_code
     *   params  string cp_id
     *   params  string operator  id
     *   return
     */
    public function isRepeatGoodsSnCode($data = [])
    {
        $res = ['code' => '001', 'msg' => ''];
        if (!isset($data['goods_sn_code'])) {
            $res['msg'] = '条码不能为空';
            return $res;
        }
        if (!isset($data['cp_id'])) {
            $res['msg'] = '查询条码数据异常';
            return $res;
        }
        $where[] = ['goods_sn_code', $data['goods_sn_code']];
        $where[] = ['cp_id', $data['cp_id']];
//        $where[] = ['audit_status' => 1];
        if (isset($data['operator']) && isset($data['id'])) {
            $where[] = ['id', '<>', $data['id']];
        }
        //未审核条码已存在，禁止入入库表
        $existUnAuditInfoList = GoodsStockinInfolist::where($where)->first();
        $existGoodsStockList = GoodsStockList::where($where)->where(['is_del' => 1])->first();

        if (!empty($existUnAuditInfoList)) {
            if ($existUnAuditInfoList->audit_status == 1) {
                $res['msg'] = '条码：' . $data['goods_sn_code'] . '已存在';
                return $res;
            } else {
                if ($existUnAuditInfoList->audit_status == 2 && !empty($existGoodsStockList)) {
                    $res['msg'] = '条码：' . $data['goods_sn_code'] . '已存在';
                    return $res;
                }
            }
        }

        if ($existGoodsStockList) {
            $res['msg'] = '条码：' . $data['goods_sn_code'] . '已存在';
            return $res;
        }


        $res['code'] = '000';
        $res['msg'] = '条码正常';
        return $res;
    }


    /**
     *   判定条码是否重复
     *   1. 未审核数据，条码存在入库表，不可入库
     *   2. 未审核数据，删除后，可重新入库
     *   3. 已审核数据，库存表未删除，不可入库
     *   4. 已审核数据，删除库存表，可以入库
     *
     *   params  string goods_sn_code
     *   params  string cp_id
     *   params  string operator  id
     *   return
     */
    public function checkInGoods($cp_id, $goods_sn_codes)
    {

        //未审核条码已存在，禁止入入库表
        $list = GoodsStockinInfolist::query()
            ->where('cp_id', $cp_id)
            ->whereIn('goods_sn_code', $goods_sn_codes)
            ->get(['goods_sn_code', 'audit_status'])
            ->toArray();
        $stockList = GoodsStockList::query()
            ->where('cp_id', $cp_id)
            ->where(['is_del' => 1])
            ->whereIn('goods_sn_code', $goods_sn_codes)
            ->get(['goods_sn_code', 'id'])
            ->pluck(null, 'goods_sn_code')
            ->toArray();

        $res = [];
        if (!empty($stockList)) {
            foreach ($stockList as $val) {
                $res[$val['goods_sn_code']] = '条码：' . $val['goods_sn_code'] . '已存在';

            }
        }

        foreach ($list as $item) {

            if (!empty($item)) {
                if ($item['audit_status'] == 1) {
                    $res[$item['goods_sn_code']] = '条码：' . $item['goods_sn_code'] . '已存在';

                } else {
                    $goods_sn_code = $stockList[$item['goods_sn_code']] ?? [];
                    if ($item['audit_status'] == 2 && !empty($goods_sn_code)) {
                        $res[$item['goods_sn_code']] = '条码：' . $item['goods_sn_code'] . '已存在';
                    }
                }
            }
        }

        return $res;
    }


    /**
     * 电子秤入库打印
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function stockinPrint(Request $request)
    {

        $goods = $request->all();
        if (empty($goods)) {
            return response()->json(['code' => '001', 'msg' => '数据不能为空']);
        }


        $goodscheck = [
            'store_id', 'goods_sn_code', 'goods_img', 'pricetype', 'odds', 'goods_name', 'goods_style_id', 'goods_category_id', 'stockin_at', 'supply_id', 'count', 'gramprice_fee', 'label_price',
            'pieceprice_fee', 'piece_weight', 'netglod_weight', 'content', 'costglod_price', 'costpiece_fee', 'costgram_fee', 'piececost_fee', 'goods_craft_id', 'c_no', 's_no',
            'gemstone_fee1', 'gemstone_fee2', 'add_fee1', 'add_fee2', 'goods_brand_id', 'cf_no', 'cf_no_gia', 'cf_fee', 'main_stone_weigth', 'main_stone_count', 'other_stone_weigth',
            'other_stone_count', 'color', 'clarity', 'main_stone_val', 'other_stone_val', 'cut', 'goods_pricetype_id', 'goods_stone_id', 'procure_at', 'paytype_id', 'paymoney', 'remark',
            'total_piece_weight', 'total_netglod_weight', 'is_code_more', 'goods_content_id', 'temp_id',
        ];
        $temp_id = $goods['temp_id'] ?? 0;
        unset($goods['temp_id']);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $Validate = new ValidateGoodsGoodsStockin();
        if (!$Validate->check($goods)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }


        $data = [];
        $goods['pieceprice_fee'] = empty($goods['pieceprice_fee']) ? 0 : $goods['pieceprice_fee'] * 100;
        $goods['costpiece_fee'] = empty($goods['costpiece_fee']) ? 0 : $goods['costpiece_fee'] * 100;
        $goods['costgram_fee'] = empty($goods['costgram_fee']) ? 0 : $goods['costgram_fee'] * 100;
        $goods['gramprice_fee'] = empty($goods['gramprice_fee']) ? 0 : $goods['gramprice_fee'] * 100;
        $goods['piececost_fee'] = empty($goods['piececost_fee']) ? 0 : $goods['piececost_fee'] * 100;
        $goods['costglod_price'] = empty($goods['costglod_price']) ? 0 : $goods['costglod_price'] * 100;
        $goods['paymoney'] = empty($goods['paymoney']) ? 0 : $goods['paymoney'] * 100;
        $goods['add_fee1'] = empty($goods['add_fee1']) ? 0 : $goods['add_fee1'] * 100;
        $goods['add_fee2'] = empty($goods['add_fee2']) ? 0 : $goods['add_fee2'] * 100;

        foreach ($goods as $key => $good) {
            if (in_array($key, $goodscheck) && !empty($good)) {
                $data[$key] = $good;
            }
        }


        if (!empty($data)) {
            $data['cp_id'] = $cp_id;
            $data['total_netglod_weight'] = $data['netglod_weight'] * $data['count'];
            $data['total_piece_weight'] = ($data['piece_weight'] ?? 0) * $data['count'];
            $id = GoodsStockinPrint::query()
                ->create($data)->id;
            $printIds = implode(',', [$id]);

            $url = env('APP_URL') . "/store/basic/templatetag/tagPrint?id=$temp_id&type=4&cp_id=$cp_id&stockIds=$printIds";

            return response()->json(['code' => '000', 'url' => $url]);
        } else {
            return response()->json(['code' => '001', 'msg' => '数据获取失败']);
        }

    }
}
